/*
 * @Descripttion:
 * @version:
 * @Author: pyq
 * @Date: 2024-10-15 17:08:17
 * @LastEditors: pyq
 * @LastEditTime: 2024-10-18 22:30:33
 */
// src/app.js
import dotenv from "dotenv";
import Koa from "koa";
import router from "./routes/index.js";
import { koaSwagger } from "koa2-swagger-ui";
import swagger from "./config/swagger.js";
import cors from "@koa/cors";
import errorHandler from "./middleware/errorHandler.js";
import authMiddleware from "./middleware/authMiddleware.js";
import { koaBody } from "koa-body";

dotenv.config();
const app = new Koa();
app.use(
    koaBody({
        multipart: true,
        formidable: {
            maxFileSize: 200 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
        },
    })
);

// 启用 CORS
app.use(
  cors({
    origin: "*", // 允许所有域名请求，如果只想允许特定域名，可以设置为对应的域名
    allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allowHeaders: ["Content-Type", "Authorization", "Accept"],
  })
);

// swagger配置
app.use(swagger.routes(), swagger.allowedMethods());
app.use(
  koaSwagger({
    routePrefix: "/swagger",
    swaggerOptions: {
      url: "/swagger.json",
    },
  })
);

app.use(errorHandler); // 全局异常处理
app.use(authMiddleware);

router.get("/", (ctx) => {
  ctx.body = "Hello Koa!";
});

const PORT = process.env.PORT || 3000;

app.use(router.routes()).use(router.allowedMethods());

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
